from geocoder import ip
from geocoder.ipinfo import IpinfoQuery
from requests import get
from typing import Optional
from rich.table import Table
from rich.console import Console
from utils import (
    config,
    WeatherNow,
    Unit, Language,
    get_location,
    format_time
)
from utils.type import _WeatherNow

def weather_now(
        location: Optional[str]=None,
        language: Language=None,
        unit: Unit=None
    ) -> _WeatherNow:
    """
    Get weather for now

    Args:
        location: Location to get weather forcast. Default: `None`
        language: Language to get weather forcast. Default: `None`
        unit: Unit to get weather forcast. Default: `None`

    Returns:
        Weather for now
    """
    # Get location
    if location is None:
        location = 'me'
        g: IpinfoQuery = ip(location, timeout=1)
        loc = ','.join([str(g.latlng[1]), str(g.latlng[0])])
    else:
        loc = get_location(location)
    # Get language and unit
    if language is None:
        language = config.language
    if unit is None:
        unit = config.unit
    # Get qweather api
    base_url = f'{config.base_url}/v7/weather/now?location={loc}&lang={language}&unit={unit}'
    headers = {'Authorization': f'Bearer {config.token}'}
    # Send request and get response in json format
    resp = get(url=base_url, headers=headers)
    result: WeatherNow = resp.json()
    if 'now' in result:
        return result['now']

def print_now(
        table: _WeatherNow,
        unit: Unit=None
    ) -> None:
    """
    Print weather for now with table

    Args:
        table: Weather for now
        unit: Unit. Default: `None`
    """
    # Get default unit
    if unit is None:
        unit = config.unit
    # Create Console
    console = Console()
    # Create Table
    t = Table(title='🌤️ Weather for now', header_style='bold magenta')
    t.add_column('NAME', style='cyan')
    t.add_column('VALUE', style='green')
    # Initialize field mapping
    field_mapping = {
        'obsTime': ('观测时间', format_time(table['obsTime'], '%Y/%m/%d %H:%M')),
        'temp': ('温度', table['temp'] + '°C' if unit == 'm' else '°F'),
        'feelsLike': ('体感温度', table['feelsLike'] + '°C' if unit == 'm' else '°F'),
        'text': ('天气状况', table['text']),
        'windDir': ('风向', table['windDir']),
        'windScale': ('风力等级', table['windScale'] + '级'),
        'windSpeed': ('风速', table['windSpeed'] + 'km/h' if unit == 'm' else 'mph'),
        'humidity': ('相对湿度', table['humidity'] + '%'),
        'precip': ('降水量', table['precip'] + 'mm' if unit == 'm' else 'in'),
        'pressure': ('大气压强', table['pressure'] + 'hPa'),
        'vis': ('能见度', table['vis'] + 'km' if unit == 'm' else 'mi'),
        'cloud': ('云量', table['cloud'] + '%'),
        'dew': ('露点温度', table['dew'] + '°C' if unit == 'm' else '°F')
    }
    # Add rows to table
    for _, (name, value) in field_mapping.items():
        t.add_row(name, str(value))
    # Print table
    console.print(t)
